package beikai.com.assistant.service.impl;

import beikai.com.assistant.common.domain.params.UserPaymentParams;
import beikai.com.assistant.common.exception.EleException;
import beikai.com.assistant.common.util.DateUtil;
import beikai.com.assistant.common.util.NumberUtil;
import beikai.com.assistant.common.util.R;
import beikai.com.assistant.dao.mapper.UserPaymentMapper;
import beikai.com.assistant.dao.model.UserPaymentModel;
import beikai.com.assistant.dao.model.VillageDetailModel;
import beikai.com.assistant.service.IUserPaymentService;
import beikai.com.assistant.service.IVillageDetailService;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户消费记录 服务实现类
 * </p>
 *
 * @author beikai
 * @since 2021-12-19
 */
@Service
public class UserPaymentServiceImpl extends ServiceImpl<UserPaymentMapper, UserPaymentModel> implements IUserPaymentService {

    @Autowired
    private IVillageDetailService villageDetailService;

    @Override
    public JSONObject addPay(UserPaymentParams userPaymentParams) {
        for (Map.Entry<Long, String> paymentDetail : userPaymentParams.getParams().entrySet()) {
            VillageDetailModel villageDetailModel = villageDetailService.getDetailById(paymentDetail.getKey());
            if (Objects.isNull(villageDetailModel)) {
                continue;
            }
            UserPaymentModel userPaymentModel = new UserPaymentModel();
            userPaymentModel.setUserId(userPaymentParams.getUserId());
            userPaymentModel.setPayDate(StrUtil.isBlank(userPaymentParams.getDate()) ? DateUtil.getStringDate(LocalDateTime.now(), DateUtil.YEAR_MONTH) : userPaymentParams.getDate());
            userPaymentModel.setVillageId(userPaymentParams.getVillageId());
            userPaymentModel.setDetailId(paymentDetail.getKey());
            userPaymentModel.setValue(NumberUtil.yuanToFen(paymentDetail.getValue()));
            userPaymentModel.setUnitPrice(villageDetailModel.getValue());
            if (!addPayment(userPaymentModel)) {
                throw new EleException("录入系统出错!");
            }
        }
        return R.success();
    }

    private Boolean addPayment(UserPaymentModel userPaymentModel) {
        UserPaymentModel one = getOne(Wrappers.lambdaQuery(new UserPaymentModel())
                .eq(UserPaymentModel::getIsDelete, false)
                .eq(UserPaymentModel::getUserId, userPaymentModel.getUserId())
                .eq(UserPaymentModel::getDetailId, userPaymentModel.getDetailId())
                .eq(UserPaymentModel::getPayDate, userPaymentModel.getPayDate())
                .eq(UserPaymentModel::getVillageId, userPaymentModel.getVillageId())
                .last("limit 1")
        );
        if (Objects.isNull(one)) {
            return save(userPaymentModel);
        } else {
            userPaymentModel.setId(one.getId());
            return updateById(userPaymentModel);
        }
    }

    @Override
    public JSONObject getPayInfo(UserPaymentParams userPaymentParams) {
        // 获取当前月份的值
        String currDate = StrUtil.isBlank(userPaymentParams.getDate()) ? DateUtil.getStringDate(LocalDateTime.now(), DateUtil.YEAR_MONTH) : userPaymentParams.getDate() ;
        List<UserPaymentModel> currList = getPayInfoList(userPaymentParams.getUserId(),userPaymentParams.getVillageId(), currDate);
        // 获取这月的值
        String beforeDate = DateUtil.getStringDate(DateUtil.getLocalDate(currDate, DateUtil.YEAR_MONTH).minusMonths(1).atStartOfDay(), DateUtil.YEAR_MONTH);
        List<UserPaymentModel> beforeList = getPayInfoList(userPaymentParams.getUserId(),userPaymentParams.getVillageId(), beforeDate);
        JSONObject jsonObject = new JSONObject();
        JSONObject currJson = new JSONObject();
        JSONObject beforeJson = new JSONObject();
        currJson.put("date",currDate);
        if (!CollectionUtils.isEmpty(beforeList)) {
            beforeJson.put("date",beforeDate);
        }

        double allSum = 0.0;
        Map<Long, UserPaymentModel> collect = beforeList.stream().collect(Collectors.groupingBy(UserPaymentModel::getDetailId, Collectors.collectingAndThen(Collectors.toList(), each -> each.get(0))));
        for (UserPaymentModel each : currList) {
            UserPaymentModel userPaymentModel = collect.get(each.getDetailId());
            VillageDetailModel detailById = villageDetailService.getDetailByIdIncludeDeleted(each.getDetailId());

            if (Objects.isNull(userPaymentModel)) {
                // 上一次未录入信息
                String multiply = NumberUtil.multiply(NumberUtil.fenToYuan(each.getValue()), NumberUtil.fenToYuan(each.getUnitPrice()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"值"),NumberUtil.fenToYuan(each.getValue()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"单价"),NumberUtil.fenToYuan(each.getUnitPrice()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"应付"),multiply);

                allSum += new BigDecimal(multiply).doubleValue();
            }else {
                // 上次有录入信息
                beforeJson.put(String.format("%s-%s-%s",detailById.getName(),beforeDate,"值"),NumberUtil.fenToYuan(each.getValue()));
                beforeJson.put(String.format("%s-%s-%s",detailById.getName(),beforeDate,"单价"),NumberUtil.fenToYuan(each.getUnitPrice()));

                String multiply = NumberUtil.multiply(NumberUtil.fenToYuan(each.getValue()-userPaymentModel.getValue()), NumberUtil.fenToYuan(each.getUnitPrice()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"值"),NumberUtil.fenToYuan(each.getValue()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"单价"),NumberUtil.fenToYuan(each.getUnitPrice()));
                currJson.put(String.format("%s-%s-%s",detailById.getName(),currDate,"应付"),multiply);

                allSum += new BigDecimal(multiply).doubleValue();
            }
        }

        jsonObject.put("本次费用",currJson);
        jsonObject.put("上次费用",beforeJson);
        jsonObject.put("应支付金额",allSum);


        return R.success(jsonObject);
    }

    private List<UserPaymentModel> getPayInfoList(Long userId,Long villageId, String date) {
        return list(Wrappers.lambdaQuery(new UserPaymentModel())
                .eq(UserPaymentModel::getIsDelete, false)
                .eq(UserPaymentModel::getPayDate, date)
                .eq(UserPaymentModel::getUserId, userId)
                .eq(UserPaymentModel::getVillageId, villageId)
        );
    }

}
